<template>
  <a-spin :spinning="spinning">
    <input
      type="file"
      multiple
      id="files"
      ref="refFile"
      style="display: none"
      v-on:change="fileLoad"
    />
    <div v-if="station" style="margin: 20px 0 0 0">
      <sync-model-dlg ref="syncDlg"></sync-model-dlg>
      <finder ref="finderDlg" @treesel="onFinderSelected"></finder>
      <a-space>
        <a-button @click="find">模糊查询...</a-button>
        <a-button @click="addThing">增加设备...</a-button>
        <a-button v-if="isEdge" @click="syncToCloud">同步到云端...</a-button>
        <a-button @click="deleteThings">批量删除</a-button>
        <a-button @click="importThings">批量导入...</a-button>
        <a-button @click="exportTemplate">导出模板...</a-button>
        <a-button @click="refresh">刷新</a-button>

        <!--
        <a-button @click="refresh" style="margin: 0 0 0 30px"
          >下载模板</a-button
        >-->
      </a-space>
      <p style="margin-top:15px">
        <span>总数:{{devCount}}</span> <span style="margin-left:40px">在线个数:{{onlineCount}}</span>
        <span style="margin-left:40px">离线个数:{{devCount - onlineCount}}</span>
      </p>
      <p style="margin: 10px 0 0 0">
        <template v-for="(column, index) in columns">
          <vxe-checkbox
            v-if="column.title"
            v-model="column.visible"
            :key="index"
            @change="
              $refs.xTree.refreshColumn();
              saveColumns();
            "
            >{{ column.title }}</vxe-checkbox
          >
        </template>
      </p>
      <thing-cfg-dlg ref="thingDlg"></thing-cfg-dlg>
      <a-tabs>
        <a-tab-pane key="1" tab="智能箱">
          <IPCCfg ref="ipcDlg" @add_finished="refresh"></IPCCfg>
          <vxe-table
            style="margin: 10px 0 0 0"
            size="small"
            ref="xTree"
            border="inner"
            :data="station.devs"
            @cell-dblclick="cellDBLClickEvent"
            :checkbox-config="{
              checkField: 'checked',
              highlight: false,
              range: true,
            }"
            highlight-hover-row
            stripe
            resizable
          >
            <vxe-table-column
              type="seq"
              width="60"
              fixed="left"
              tree-node
            ></vxe-table-column>
            <vxe-table-column
              type="checkbox"
              width="80"
              title="所有"
            ></vxe-table-column>
            <vxe-table-column
              field="s_name"
              title="名称"
              sortable
              :filters="[{ data: '' }]"
              :filter-method="filterNameMethod"
              :filter-recover-method="filterNameMethod"
            >
              <template #filter="{ $panel, column }">
                <template v-for="(option, index) in column.filters">
                  <input
                    class="my-input"
                    type="type"
                    :key="index"
                    v-model="option.data"
                    @input="$panel.changeOption($event, !!option.data, option)"
                    @keyup.enter="$panel.confirmFilter()"
                    placeholder="按回车确认筛选"
                  />
                </template>
              </template>
            </vxe-table-column>
            <vxe-table-column field="uid" title="ID" sortable>
            </vxe-table-column>
            <vxe-table-column field="used_time" title="启用时间">
            </vxe-table-column>
            <vxe-table-column field="buy_time" title="购买时间">
            </vxe-table-column>
            <vxe-table-column field="create_time" title="创建时间">
            </vxe-table-column>

            <vxe-table-column field="ip" title="IP" width="110" sortable>
            </vxe-table-column>
            <vxe-table-column field="business_id" title="sn" sortable>
            </vxe-table-column>
            <vxe-table-column
              field="status_used"
              title="开通状态"
              :formatter="formatterStatus"
              :filters="[{ data: '' }]"
              :filter-method="filterStatusMethod"
            >
              <template #filter="{ $panel, column }">
                <select
                  class="my-select"
                  v-model="option.data"
                  v-for="(option, index) in column.filters"
                  :key="index"
                  @change="$panel.changeOption($event, !!option.data, option)"
                >
                  <option
                    v-for="s in statusList"
                    :key="s.value"
                    :value="s.label"
                  >
                    {{ s.label }}
                  </option>
                </select>
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="state"
              title="在线状态"
              :formatter="formatterState"
              :filters="stateList"
              :filter-multiple="false"
            ></vxe-table-column>

            <vxe-table-column field="lon" title="经度"> </vxe-table-column>
            <vxe-table-column field="lat" title="纬度"> </vxe-table-column>

            <vxe-table-column fixed="right" title="操作" width="100">
              <template #default="{ row }">
                <a-space>
                  <a-icon
                    v-if="row.model_id === 'm_smartBoxForPolice'"
                    type="edit"
                    @click="editThing(row)"
                  />
                  <a-popconfirm
                    v-if="row.model_id === 'm_smartBoxForPolice'"
                    title="是否确认删除该记录？"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="removeDev(row)"
                  >
                    <a-icon type="delete" />
                  </a-popconfirm>
                  <a-icon
                    type="camera"
                    v-if="row.model_id === 'm_smartBoxForPolice'"
                    @click="addCamera(row)"
                  />
                  <a-icon
                    type="eye"
                    @click="showRealData(row)"
                    v-if="row.model_id === 'm_smartBoxForPolice'"
                  />
                </a-space>
              </template>
            </vxe-table-column>
          </vxe-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="摄像机">
          <a-button></a-button>
          <vxe-table
            style="margin: 10px 0 0 0"
            size="small"
            ref="xTreeCamera"
            show-overflow
            border="inner"
            :data="station.cameras"
            highlight-hover-row
            resizable
          >
            <vxe-table-column
              type="seq"
              width="60"
              fixed="left"
            ></vxe-table-column>
            <vxe-table-column
              field="s_name"
              title="名称"
              sortable
            ></vxe-table-column>
            <vxe-table-column field="b" title="单板"> </vxe-table-column>
            <vxe-table-column field="p" title="端口"> </vxe-table-column>
            <vxe-table-column field="uid" title="ID"> </vxe-table-column>
            <vxe-table-column field="used_time" title="启用时间">
            </vxe-table-column>
            <vxe-table-column field="buy_time" title="购买时间">
            </vxe-table-column>
            <vxe-table-column field="create_time" title="创建时间">
            </vxe-table-column>
            <vxe-table-column field="box_ip" title="智能箱ip" width="110" fixed>
            </vxe-table-column>

            <vxe-table-column field="ip" title="IP" width="110">
            </vxe-table-column>
            <vxe-table-column field="business_id" title="sn"></vxe-table-column>
            <vxe-table-column
              field="state"
              title="在线状态"
              :formatter="formatterState"
              :filters="stateList"
              :filter-multiple="false"
            ></vxe-table-column>
          </vxe-table>
        </a-tab-pane>
      </a-tabs>
    </div>
  </a-spin>
</template>
<script>
import { post, update, remove, postEx } from "@/services/crud";
import ThingCfgDlg from "../dcfg/ThingCfgDlg.vue";
import SyncModelDlg from "@/components/cfg/sync/SyncModelDlg.vue";
import { handleExcel } from "@/services/importCfg.js";
import { thingAction } from "@/services/things.js";
import Finder from "@/components/objTree/Finder";
import { getCustom, saveCustom } from "@/services/custom";
import IPCCfg from "../dcfg/IPCCfg.vue";
import { createIPCs, getIPCs, deleteCamera } from "@/services/ipc.js";
export default {
  components: {
    ThingCfgDlg,
    SyncModelDlg,
    Finder,
    IPCCfg,
  },
  computed: {
    station() {
      return this.$store.state.station.activeStation;
    },
    devCount(){
      return this.$store.state.station.activeStation?.devs?.length
    },
    onlineCount(){
      let onlines = this.$store.state.station.activeStation?.devs?.filter(dev=>{
        return dev.state == 1
      })
      return onlines?.length
    },

    isEdge() {
      return process.env.VUE_APP_TYPE === "edge";
    },
  },
  mounted() {
    // 获取所有列配置
    let self = this;
    setTimeout(() => {
      self.refresh();
    }, 1000);
  },
  data() {
    return {
      treeConfig: {
        children: "cameras",
      },
      spinning: false,
     
      stateList: [
        { label: "在线", value: 1 },
        { label: "离线", value: 0 },
      ],
      /*  <span v-if="record.status_used === -2">未知</span>
            <span v-if="record.status_used === 1">使用中</span>
            <span v-if="record.status_used === 0">停用</span>
            <span v-if="record.status_used === -1">施工中</span>*/
      statusList: [
        { label: "启用", value: 1 },
        { label: "停用", value: 0 },
        { label: "施工中", value: 2 },
        { label: "未知", value: -2 },
      ],
      columns: [],
    };
  },
  methods: {
    find() {
      this.$refs.finderDlg.Show(() => {}, this);
    },
    onFinderSelected(uid, thing) {
      //let thing = this.$store.state.thingView.thingCache[uid]
      if (thing) {
        let promiseHandler;
        if (thing.is_station === false) {
          let sid = thing.station_id;
          if (sid) {
            promiseHandler = this.$store.dispatch(
              "station/refreshActiveStation",
              sid
            );
          }
        } else {
          promiseHandler = this.$store.dispatch(
            "station/refreshActiveStation",
            uid
          );
        }
        let self = this;
        if (promiseHandler) {
          promiseHandler.then(() => {
            let item;
            if (self.station && self.station.devs) {
              let index = self.station.devs.findIndex((d) => {
                return d.uid == uid;
              });
              if (index >= 0) {
                item = self.station.devs[index];
                let fir = self.station.devs[0];
                self.$set(self.station.devs, index, fir);
                self.$set(self.station.devs, 0, item);
              }
              if (item) {
                self.$refs.xTree.setCurrentRow(item);
              }
            }
          });
        }
      }
    },
    importThings() {
      this.$refs.refFile.value = "";
      this.$refs.refFile.dispatchEvent(new MouseEvent("click"));
    },
    fileLoad() {
      let self = this;
      this.$refs.refFile.files.forEach((selectedFile) => {
        //var reader = new FileReader();
        //const record = this.currentRecord
        console.log("XXXXXXXXXXXXXXXXXXXX", selectedFile);
        handleExcel(selectedFile, (workspaces) => {
          if (workspaces && workspaces.length == 2) {
            postEx(
              "/cfg/fromFile/import/" + self.station.model_id,
              workspaces[0]
            )
              .then(() => {
                createIPCs(workspaces[1])
                  .then(() => {
                    self.$message.info("导入完成");
                  })
                  .finally(() => {
                    self.refresh();
                  })
                  .catch((err) => {
                    self.$message.info("摄像机导入失败:" + err);
                  });
              })
              .catch((err) => {
                self.$message.info("智能箱导入失败:" + err);
                self.refresh();
              });
          }
        });
      });
      this.$refs.refFile.value = "";
      //const selectedFile = this.$refs.refFile.files[0];
    },
    exportTemplate() {
      window.open("api/file/exportempty.xlsx");
    },
    filterNameMethod({ option, row }) {
      return row.s_name && row.s_name.indexOf(option.data) >= 0;
    },
    filterStatusMethod({ option, row }) {
      let value = row.status_used;
      let label = this.formatterStatus({ cellValue: value });
      return label == option.data;
    },
    formatterState({ cellValue }) {
      let index = this.stateList.findIndex((s) => {
        return s.value == cellValue;
      });
      if (index == -1) {
        return "未知";
      }
      return this.stateList[index].label;
    },
    formatterTrueFalse({ cellValue }) {
      if (cellValue == true || cellValue == "true" || cellValue == 1) {
        return "是";
      }
      return "否";
    },
    formatterStatus({ cellValue }) {
      let index = this.statusList.findIndex((s) => {
        return s.value == cellValue;
      });
      if (index == -1) {
        return "未知";
      }
      return this.statusList[index].label;
    },
    thingsToCloud(child) {
      var edge;
      this.station.devs.forEach((dev) => {
        if (dev.model_id == "IOTBASEmEdgeCTL") {
          edge = dev;
        }
      });
      if (edge) {
        //{ things, pd, un, edgeID,addr }
        return this.$store.dispatch("station/syncStationToCloud", {
          edgeID: edge.uid,
          things: this.station.devs,
          un: child.username,
          pd: child.password,
          addr: child.svrAddr,
        });
      }
    },
    syncToCloud() {
      this.$refs.syncDlg.showDlg(this.thingsToCloud);
    },

    refresh() {
      this.spinning = true;
      let _this = this;
      this.$store.dispatch("station/refreshActiveStation").finally(() => {
        _this.spinning = false;
      });
      let self = this;
      self.columns = self.$refs.xTree.getColumns();
      getCustom("user", "devlist.columns")
        .then((res) => {
          if (res && res.data && res.data.result && res.data.result[0]) {
            let cs = res.data.result[0].body;
            if (!cs) {
              self.$refs.xTree.refreshColumn();
              return;
            }
            self.columns.forEach((c) => {
              let cfound = cs.find((c2) => {
                return c.title === c2.title;
              });
              if (cfound) {
                c.visible = cfound.visible;
              } else {
                c.visible = false;
              }
            });
          }
        })
        .finally(() => {
          self.$refs.xTree.refreshColumn();
        });
    },
    cellDBLClickEvent({ row }) {
      this.editThing(row);
    },
    addThingToSvr(owner, dlg) {
      const item = dlg.$data.item;
      const count = dlg.$data.count;
      console.log("add item--------------", item);
      return thingAction(post, owner, item, count);
    },
    updateThingToSvr(owner, dlg) {
      const item = dlg.$data.item;
      console.log("update item--------------", item);
      return thingAction(update, owner, item);
    },
    addThing() {
      //this.curStation = record;
      //console.log("-------------", record);
      this.spinning = true;
      this.$refs.thingDlg.Show(this.addThingToSvr, this, {
        isNew: true,
        station: this.station,
      });
      this.spinning = false;
    },
    editThing(child) {
      //this.curStation = record;
      //console.log("-------------", record);
      this.spinning = true;
      const item = JSON.parse(JSON.stringify(child)); //Object.assign({}, child);
      item.isNew = false;
      item.station = this.station;
      this.$refs.thingDlg.Show(this.updateThingToSvr, this, item);
      this.spinning = false;
    },
    removeDev(child) {
      let _this = this;
      this.spinning = true;
      remove("thing", child.uid).finally(() => {
        _this.refresh();
        _this.spinning = false;
      });
    },
    deleteThings() {
      let devs = [];

      this.station.devs.forEach((dev) => {
        if (dev.checked) {
          devs.push(
            new Promise((re) => {
              remove("thing", dev.uid)
                .then(() => {
                  getIPCs(dev).then((ipcs) => {
                    if (ipcs) {
                      ipcs.forEach((ipc) => {
                        deleteCamera(ipc.ipc_id);
                      });
                    }
                  });
                })
                .finally(() => {
                  re();
                });
            })
          );
        }
      });
      let self = this;
      if (devs.length > 0) {
        this.spinning = true;
        Promise.all(devs).finally(() => {
          self.spinning = true;
          self.refresh();
        });
      }
    },
    saveColumns() {
      let infos = this.$refs.xTree.getColumns().map((x) => {
        return {
          visible: x.visible,
          title: x.title,
        };
      });
      let item = { body: infos, c_type: "user", s_name: "devlist.columns" };
      saveCustom(item);
    },
    showRealData(row) {
      this.$store
        .dispatch("thingView/refreshActiveThing", row.uid)
        .finally(() => {
          this.$router.push("/real/");
        });
    },
    addCamera(row) {
      row.station_id = this.station.uid;
      this.$refs.ipcDlg.showDlg(row);
    },
  },
};
</script>
<style>
.vxe-table--filter-wrapper {
  background-color: rgb(64, 64, 66);
  color: red;
}
.vxe-cell .vxe-input > .vxe-input--inner,
.vxe-cell .vxe-textarea > .vxe-textarea--inner,
.vxe-table--filter-wrapper .vxe-input > .vxe-input--inner,
.vxe-table--filter-wrapper .vxe-textarea > .vxe-textarea--inner {
  padding: 0 2px;
  color: rgb(30, 30, 228);
}
</style>